package com.yf.customdubbo;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class RpcServerHandler extends ChannelInboundHandlerAdapter{
    private Map<String,Object> handlerMap=new HashMap<>();

    public RpcServerHandler(Map<String,Object> handlerMap){
        this.handlerMap=handlerMap;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {
        RpcRequest request=(RpcRequest)msg;

        Object result=new Object();

        //根据request进行调用server的对应类的方法

        if(handlerMap.containsKey(request.getClassName())){
            //执行服务端对应的对象
            Object clazz=handlerMap.get(request.getClassName());
            Method method=clazz.getClass().getMethod(request.getMethondName(),request.getTypes());
            result=method.invoke(clazz,request.getParams());
        }
        //把运行完成的result写给客户端
        ctx.write(result);
        ctx.flush();
        ctx.close();
    }

}
